//
//  PCDApiChooseImage.m
//  PCDMPaasBank
//
//  Created by DK on 2021/3/9.
//  Copyright © 2021 Alibaba. All rights reserved.
//

#import "PCDApiChooseImage.h"
#import "TZImagePickerController.h"
#import "PCDPageViewMange.h"

#define AresPic @"AresPic"

@interface PCDApiChooseImage ()<TZImagePickerControllerDelegate>
/// 图片路径
@property (nonatomic, copy) NSString *picPath;
@end

@implementation PCDApiChooseImage

- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback
{
    
    //
    self.bsContext = context;
    
    NSString *locationPath = [NSString stringWithFormat:@"%@/%@",PackageSericePath,[PCDUtil channelAPPID]];
    if (![PCDFile fileExistsAtPath:locationPath]) {
        [PCDFile createDirectoryAtPath:locationPath];
    }
    self.picPath = [locationPath stringByAppendingPathComponent:AresPic];
    
    NSDictionary *dict;
    if ([data isKindOfClass:[NSDictionary class]]) {
        dict = (NSDictionary*)data;
    }else{
        dict =(NSDictionary*)[data JSONValue];
    }
    
    
    NSString *sourceType = [dict objectForKey:@"sourceType"];
    if ([sourceType integerValue] == 2) {
        [self photoLibraryWithParma:dict];
    } else if ([sourceType integerValue] == 1) {
        [self takePhotoWithParma:dict];
    } else {
    
        UIAlertController *alertViewVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *alertPhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePhotoWithParma:dict];
        }];
        [alertViewVC addAction:alertPhoto];
        UIAlertAction *alertAblum = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self photoLibraryWithParma:dict];
        }];
        [alertViewVC addAction:alertAblum];
        UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertViewVC addAction:alertCancel];
        
        UIViewController *vc = self.bsContext.viewController;
        [vc presentViewController:alertViewVC animated:YES completion:nil];
    }
    
}

- (void)takePhotoWithParma:(NSDictionary *)parma {
    
    //相机权限判断
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        PCDLog(@"不支持相机");
        return;
    }
    float RepresentationF = 1.0f;
    NSArray *sizeType = [parma objectForKey:@"sizeType"];
    if ([sizeType containsObject:@"compressed"]) {
        //默认压缩比例0.8
        RepresentationF = 0.8f;
    }
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    __weak typeof(self) weakSelf = self;
    picker.completionBlock = ^(UIImagePickerController *pickerController, NSDictionary *info){
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        NSData *imageOriginData = nil;
        if ([weakSelf imageHasAlpha: image]) {
            imageOriginData = UIImagePNGRepresentation(image);
        } else {
            imageOriginData = UIImageJPEGRepresentation(image,RepresentationF);
        }
        //压缩
        if (imageOriginData.length>1*1024*1024) { //超过1M，继续压缩
            UIImage * dealImg = [self reSizeImage:image toSize:CGSizeMake(kMainScreenWidth, kMainScreenHeight)];
            if ([weakSelf imageHasAlpha: dealImg]) {
                imageOriginData = UIImagePNGRepresentation(dealImg);
            } else {
                imageOriginData = UIImageJPEGRepresentation(dealImg,1.0);
            }
        }
        //使用当前
        NSString *imageID = [NSString stringWithFormat:@"%@.jpg",[PCDUtil md5StringWithData:imageOriginData]];
        NSString *locationPath = self.picPath;
        
        NSString *filePath = [locationPath stringByAppendingPathComponent:imageID];
        if (![PCDFile fileExistsAtPath:locationPath]) {
            [PCDFile createDirectoryAtPath:locationPath];
        }
        
        [imageOriginData writeToFile:filePath atomically:YES];
        
        NSMutableArray *tempFilePathsArray = [NSMutableArray array];
        NSMutableArray *tempFilesArray = [NSMutableArray array];
        NSString *tempFilePath = [NSString stringWithFormat:@"%@/%@/%@",[PCDUtil channelAPPID],AresPic,imageID];
        //添加本地服务端口
        tempFilePath = [NSString stringWithFormat:@"%@/%@",[[PCDPackageUitil sharedService] getSericeUrl],tempFilePath];
        [tempFilePathsArray addObject:tempFilePath];
        NSNumber *size = [NSNumber numberWithInteger:[imageOriginData length]];
        NSDictionary *dictionary = @{@"path":tempFilePath,@"size":size};
        [tempFilesArray addObject:dictionary];
        NSDictionary *dic= @{@"tempFilePaths":tempFilePathsArray,@"tempFiles":tempFilesArray};
        
        evaluateJavaScriptOnMainThread(self, [parma objectForKey:@"success"], [dic JSONRepresentation]);
        [pickerController dismissViewControllerAnimated:YES completion:NULL];
    };
    
    picker.cancelBlock = ^(UIImagePickerController *picker){
        [picker dismissViewControllerAnimated:YES completion:NULL];
    };
    
    UIViewController *vc = self.bsContext.viewController;
    picker.modalPresentationStyle = UIModalPresentationFullScreen;
    [vc presentViewController:picker animated:YES completion:NULL];
}


- (void)photoLibraryWithParma:(NSDictionary *)parma{
    
    //如果不传 默认可以选9张
    NSInteger count = 9;
    if ([parma objectForKey:@"count"] != nil) {
        count = [[parma objectForKey:@"count"] integerValue];
    }
    
    float RepresentationF = 1.0f;
    NSArray *sizeType = [parma objectForKey:@"sizeType"];
    if ([sizeType containsObject:@"compressed"]) {
        //默认压缩比例0.8
        RepresentationF = 0.8f;
    }
    __weak typeof(self) weakSelf = self;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (photos.count > 1) {
            NSMutableArray *tempFilePathsArray = [NSMutableArray array];
            NSMutableArray *tempFilesArray = [NSMutableArray array];
            for (UIImage *image in photos) {
                NSData *imageOriginData = nil;
                if ([weakSelf imageHasAlpha: image]) {
                    imageOriginData = UIImagePNGRepresentation(image);
                } else {
                    imageOriginData = UIImageJPEGRepresentation(image,RepresentationF);
                }
                //压缩
                if (imageOriginData.length>1*1024*1024) { //超过1M，继续压缩
                    UIImage * dealImg = [self reSizeImage:image toSize:CGSizeMake(kMainScreenWidth, kMainScreenHeight)];
                    if ([weakSelf imageHasAlpha: dealImg]) {
                        imageOriginData = UIImagePNGRepresentation(dealImg);
                    } else {
                        imageOriginData = UIImageJPEGRepresentation(dealImg,1.0);
                    }
                }
                
                NSString *imageID = [NSString stringWithFormat:@"%@.jpg",[PCDUtil md5StringWithData:imageOriginData]];
                NSString *locationPath = self.picPath;

                NSString *filePath = [locationPath stringByAppendingPathComponent:imageID];
                
                if (![PCDFile fileExistsAtPath:locationPath]) {
                    [PCDFile createDirectoryAtPath:locationPath];
                }
                [imageOriginData writeToFile:filePath atomically:YES];
                NSString *tempFilePath = [NSString stringWithFormat:@"%@/%@/%@",[PCDUtil channelAPPID],AresPic,imageID];
                //添加本地服务端口
                tempFilePath = [NSString stringWithFormat:@"%@/%@",[[PCDPackageUitil sharedService] getSericeUrl],tempFilePath];
                [tempFilePathsArray addObject:tempFilePath];
                NSNumber *size = [NSNumber numberWithInteger:[imageOriginData length]];
                NSDictionary *dictionary = @{@"path":tempFilePath,@"size":size};
                [tempFilesArray addObject:dictionary];
            }
            
            NSDictionary*dic = @{@"tempFilePaths":tempFilePathsArray,@"tempFiles":tempFilesArray};
            evaluateJavaScriptOnMainThread(self, [parma objectForKey:@"success"], [dic JSONRepresentation])
            
        } else {
            
            UIImage *imageOrigin = photos[0];
            NSData *imageOriginData = nil;
            if ([weakSelf imageHasAlpha: imageOrigin]) {
                imageOriginData = UIImagePNGRepresentation(imageOrigin);
            } else {
                imageOriginData = UIImageJPEGRepresentation(imageOrigin,RepresentationF);
            }
            //压缩
            if (imageOriginData.length>1*1024*1024) { //超过1M，继续压缩
                UIImage * dealImg = [self reSizeImage:imageOrigin toSize:CGSizeMake(kMainScreenWidth, kMainScreenHeight)];
                if ([weakSelf imageHasAlpha: dealImg]) {
                    imageOriginData = UIImagePNGRepresentation(dealImg);
                } else {
                    imageOriginData = UIImageJPEGRepresentation(dealImg,1.0);
                }
            }
            
            NSString *imageID = [NSString stringWithFormat:@"%@.jpg",[PCDUtil md5StringWithData:imageOriginData]];
            NSString *locationPath = self.picPath;

            if (![PCDFile fileExistsAtPath:locationPath]) {
                [PCDFile createDirectoryAtPath:locationPath];
            }
            NSString *filePath = [locationPath stringByAppendingPathComponent:imageID];
            [imageOriginData writeToFile:filePath atomically:YES];
            NSMutableArray *tempFilePathsArray = [NSMutableArray array];
            NSMutableArray *tempFilesArray = [NSMutableArray array];
            NSString *tempFilePath = [NSString stringWithFormat:@"%@/%@/%@",[PCDUtil channelAPPID],AresPic,imageID];
            //添加本地服务端口
            tempFilePath = [NSString stringWithFormat:@"%@/%@",[[PCDPackageUitil sharedService] getSericeUrl],tempFilePath];
            [tempFilePathsArray addObject:tempFilePath];
            NSNumber *size = [NSNumber numberWithInteger:[imageOriginData length]];
            NSDictionary *dictionary = @{@"path":tempFilePath,@"size":size};
            [tempFilesArray addObject:dictionary];
            NSDictionary *dic= @{@"tempFilePaths":tempFilePathsArray,@"tempFiles":tempFilesArray};
            
            evaluateJavaScriptOnMainThread(self, [parma objectForKey:@"success"], [dic JSONRepresentation])
            
        }
        
    }];
    UIViewController *vc = self.bsContext.viewController;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [vc presentViewController:imagePickerVc animated:YES completion:nil];
}


- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
- (NSString *)getCurrentTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

@end
